<template>
    <div>
        <!--工具条-->
        <el-form>
            <el-form-item>
                <el-button type="primary" @click="showCategory('add')" size="mini">添加</el-button>
            </el-form-item>
        </el-form>

        <el-dialog
                :title="categoryFormTitle"
                :visible.sync="categoryFormVisible"
                :before-close="emptyForm">
            <el-form :model="categoryForm" :rules="rules" ref="categoryForm" label-width="100px" class="demo-ruleForm">

                <el-form-item label="上级分类" v-if="categorySuperior != ''">
                    <el-input v-model="categorySuperior" :disabled="true"></el-input>
                </el-form-item>

                <el-form-item label="分类编号" prop="code" v-if="categorySuperior != ''">
                    <el-input placeholder="分类编号" v-model="categoryForm.code">
                        <template slot="prepend">{{ $store.state.category.code }}</template>
                    </el-input>
                </el-form-item>

                <el-form-item label="分类编号" prop="code" v-if="categorySuperior == ''">
                    <el-input v-model="categoryForm.code" :disabled="categoryDisabled"></el-input>
                </el-form-item>
                <el-form-item label="分类名称" prop="title">
                    <el-input v-model="categoryForm.title"></el-input>
                </el-form-item>
                <el-form-item label="顺序号" prop="sortNum">
                    <el-input v-model.number="categoryForm.sortNum"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer" >
                <el-button @click="resetForm" size="mini">取 消</el-button>
                <el-button type="primary" @click="categoryFormSubmit" size="mini">确 定</el-button>
            </div>
        </el-dialog>
        <tree-grid @transferFormVisibleIs="getFormVisibleIs" @tarnsAddReviseFormIs="getAddReviseFromIs" :columns="columns" :tree-structure="true" :data-source="dataSource"></tree-grid>


    </div>
</template>
<script>
  import { TreeGrid } from '../treeTable'
  import * as api from '../../../api/enjoylove_api'

  export default {
    data () {
      return {
        categoryFormVisible: false,     //是否显示弹窗
        categoryFormTitle: '',          //弹窗标题
        categoryDisabled: true,         //分类编号是否可编辑
        categorySuperior: '',           //上级分类

        categoryForm: {
          code: '',
          title: '',
          sortNum: '',
          parent: ''
        },
        rules: {
          code: [
            {required: true, message: '请输入分类编号', trigger: 'blur' },
            { min: 2, max: 2, message: '长度在 2 个字符', trigger: 'blur' }
            ],
          title: [{required: true, message: '请输入分类名称', trigger: 'blur' }],
          sortNum: [{pattern: /^[1-9]\d{0,9}$/, required: true, message: '顺序号必须为1-9位数字值'}]
        },
        columns: [
          {
            text: '分类编码',
            dataIndex: 'code'
          },
          {
            text: '分类名称',
            dataIndex: 'title'
          },
          {
            text: '顺序号',
            dataIndex: 'sortNum'
          },
          {
            text: '分类状态',
            dataIndex: 'state'
          }
        ],
        dataSource: []
      }
    },
    components: {
      TreeGrid
    },
    methods: {
      //获取分类列表
      getCategory () {
        let para = {};
        this.listLoading = true;
        api.getCategoryList(para).then((res) => {
          let datas = JSON.parse(res.data);
          if(!datas.status){
            if(datas.success){

              let dataArr = datas.data.categories;
              dataArr.forEach((val) => {
                if (val.children){
                  val.children.forEach((val) => {
                    return val.state == 0 ? val.state='<span style="color:#67c23a">正常</span>' : val.state='<span style="color:#909399">下架</span>'
                  })
                }
                return val.state == 0 ? val.state='<span style="color:#67c23a">正常</span>' : val.state='<span style="color:#909399">下架</span>'
              })

              //成功
              this.dataSource = dataArr;
              this.listLoading = false;
            }else {
              this.$message.error(datas.message);
            }
          }else{
            if(datas.status == 401){
              this.$router.push('/login');
            }
            this.$message(res.data.msg);
          }
        });
      },

      //添加一级分类弹窗
      showCategory () {
        this.categoryFormVisible = true
        this.categoryFormTitle = '添加分类'
        this.categoryDisabled = false
        this.categorySuperior = ''
      },

      //添加一级分类提交
      addCategory () {
        this.$refs['categoryForm'].validate((valid) => {
          if (valid) {
            let para = {
              title: this.categoryForm.title,
              code: this.categoryForm.code,
              sortNum: this.categoryForm.sortNum,
              parent: this.$store.state.category.id
            };

            api.addCategory(para).then(res => {
              let datas = JSON.parse(res.data);
              console.log(datas)
              if(!datas.status){
                if(datas.success){
                  //成功
                  this.$message({
                    message: '添加成功！',
                    type: 'success'
                  });
                  this.categoryFormVisible = false;
                    this.categoryForm = {
                        code: '',
                        title: '',
                        sortNum: '',
                        parent: ''
                    }
                  this.getCategory()
                  this.$refs['categoryForm'].resetFields();
                }else {
                  this.$message.error(datas.message);
                }
              }else{
                if(datas.status == 401){
                  this.$router.push('/login');
                }
                this.$message(res.data.msg);
              }
            })
          } else {
            console.log('error submit!!');
            return false
          }
        })
      },

      //修改分类弹窗
      getFormVisibleIs (msg) {
        this.categoryFormVisible = msg
        this.categoryFormTitle = '修改分类'
        this.categoryDisabled = true
        this.categorySuperior = ''
        this.categoryForm = {
          code: this.$store.state.category.code,
          title: this.$store.state.category.title,
          sortNum: this.$store.state.category.sortNum
        }
      },

      //添加二级分类弹窗
      getAddReviseFromIs (msg) {
        this.categoryFormVisible = msg
        this.categoryFormTitle = '添加二级分类'
        this.categorySuperior = this.$store.state.category.code + '-' + this.$store.state.category.title
        this.categoryDisabled = false
      },

      //修改分类提交
      updateCategory () {
        let para = {
          id: this.$store.state.category.id,
          title: this.categoryForm.title,
          sortNum: this.categoryForm.sortNum
        }

        api.updateCategory(para).then(res => {
          let datas = JSON.parse(res.data);

          if(!datas.status){
            if(datas.success){
              //成功
              this.$message({
                message: '添加成功！',
                type: 'success'
              });
              this.categoryFormVisible = false;
                this.categoryForm = {
                    code: '',
                    title: '',
                    sortNum: '',
                    parent: ''
                }
              this.getCategory()
              this.$refs['categoryForm'].resetFields();
            }else {
              this.$message.error(datas.message);
            }
          }else{
            if(datas.status == 401){
              this.$router.push('/login');
            }
            this.$message(res.data.msg);
          }
        })
      },

      categoryFormSubmit () {
        switch (this.categoryFormTitle) {
          case '添加分类':
            this.addCategory()
            break;
          case '添加二级分类':
            this.addCategory()
            break;
          case '修改分类':
            this.updateCategory()
            break;
        }
      },
      resetForm () {
        this.$refs['categoryForm'].resetFields();
          this.categoryForm = {
              code: '',
              title: '',
              sortNum: '',
              parent: ''
          }
        this.categoryFormVisible = false;
      },
      //清空表单信息
      emptyForm (done) {
        done()
        this.$refs['categoryForm'].resetFields();
        this.categoryForm = {
          code: '',
          title: '',
          sortNum: '',
          parent: ''
        }
      }
    },
    mounted() {
      this.$nextTick(() => this.getCategory())
    }
  };
</script>
